package com.hfut.jpoa.common.util;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

public class PinYin4jUtil
{

	private static HanyuPinyinOutputFormat format = null;

	private String[] pinyin;

	static
	{
		format = new HanyuPinyinOutputFormat();
		format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
		format.setVCharType(HanyuPinyinVCharType.WITH_V);
		format.setCaseType(HanyuPinyinCaseType.UPPERCASE);
	}

	// 转换单个字符

	public String getCharacterPinYin(char c)

	{

		try

		{

			pinyin = PinyinHelper.toHanyuPinyinStringArray(c, format);

		}

		catch (BadHanyuPinyinOutputFormatCombination e)

		{

			e.printStackTrace();

		}

		// 如果c不是汉字，toHanyuPinyinStringArray会返回null

		if (pinyin == null)
			return null;

		// 只取一个发音，如果是多音字，仅取第一个发音

		return pinyin[0];

	}

	/**
	 * 获取字符串内的所有汉字的汉语拼音并大写每个字的首字母
	 * 
	 * @param chinese
	 * @return
	 */
	public static String spell(String chinese)
	{
		if (chinese == null)
		{
			return null;
		}

		try
		{
			StringBuilder sb = new StringBuilder();
			for (int i = 0; i < chinese.length(); i++)
			{
				String[] array = PinyinHelper.toHanyuPinyinStringArray(
				        chinese.charAt(i), format);
				if (array == null || array.length == 0)
				{
					continue;
				}
				String s = array[0];// 不管多音字,只取第一个
				char c = s.charAt(0);// 大写第一个字母
				String pinyin = String.valueOf(c).toUpperCase();
//				String pinyin = String.valueOf(c).toUpperCase()
//						.concat(s.substring(1));
				sb.append(pinyin);
			}
			return sb.toString();
		} catch (BadHanyuPinyinOutputFormatCombination e)
		{
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 得到一个字符串
	 * 
	 * @param str
	 * @return
	 */
	public String getStringPinYin(String str)

	{

		StringBuilder sb = new StringBuilder();

		String tempPinyin = null;

		for (int i = 0; i < str.length(); ++i)

		{

			tempPinyin = getCharacterPinYin(str.charAt(i));

			if (tempPinyin == null)

			{

				// 如果str.charAt(i)非汉字，则保持原样

				sb.append(str.charAt(i));

			}

			else

			{

				sb.append(tempPinyin);

			}

		}

		return sb.toString();

	}
}
